package com.aviccxzx.smarthome.UserModule;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.GosUserModuleBaseActivity;
import com.aviccxzx.smarthome.entity.CamListBean;
import com.aviccxzx.smarthome.entity.GetMoveInfoBean;
import com.aviccxzx.smarthome.entity.addMoveLgoic;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;


/**
 * Created by joey on 2016/10/25.
 */
public class MoveDetailAct extends GosUserModuleBaseActivity implements View.OnClickListener {
    private AlertDialog alertDialog;
    private LinearLayout layout;
    private LinearLayout thenlayout;
    TextView setif_tv, setthen_tv;
    EditText move_name;
    String scene_id, move_tag, move_id = "";
    List<GizWifiDevice> mythenlist = new ArrayList<>();
    String macIf = "";
    String nameIf = "";
    String typeIf = "";
    String moveName, ifContent, thenContent = "";
    List<addMoveLgoic.ExcuteTasksBean> excuteTasks = new ArrayList<addMoveLgoic.ExcuteTasksBean>();
    List<addMoveLgoic.LogicConditionsBean> logicConditions = new ArrayList<>();
    List<CamListBean.DataBean> cams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.move_detail_lay_v19);
        } else {
            //            setContentView(R.layout.aboutus_lay);
        }
        initView();
        getCamList();
        seListener();
        if (!TextUtils.isEmpty(move_tag)) {
            move_id = getIntent().getStringExtra("move_id");
            getMoveInfo();
        }
    }

    public void getCamList() {
        progressDialog.show();
        cams = new ArrayList<>();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<CamListBean> call = service.getCamlist();
        call.enqueue(new Callback<CamListBean>() {
            @Override
            public void onResponse(Call<CamListBean> call, Response<CamListBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    cams.clear();
                    cams.addAll(response.body().getData());
                    progressDialog.dismiss();
                } else {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<CamListBean> call, Throwable t) {
                progressDialog.dismiss();
            }
        });
    }

    String ifPk;//if条件里的设备类型
    String ifMac;//if条件里的设备mac
    int thentype;//then条件里的设备类型
    String thenMac;//
    public void getMoveInfo() {
        progressDialog.show();
        String uid = spf.getString("Uid", "");
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<GetMoveInfoBean> call = service.getSceneLogicInfo(move_id, uid);
        call.enqueue(new Callback<GetMoveInfoBean>() {
            @Override
            public void onResponse(Call<GetMoveInfoBean> call, Response<GetMoveInfoBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    GetMoveInfoBean.DataBean bean = response.body().getData();

                    int iftype = bean.getConditionVos().get(0).getDevice_type();
                    thentype = bean.getExcuteTaskVos().get(0).getDevice_type();

                    String[] typeNames = new String[]{"声光报警器", "漏水探测器", "烟雾监测器", "可燃气体", "门磁", "摄像机"};
                    if (iftype == 5) {
                        setif_tv.setText(typeNames[iftype - 1] + "打开");
                    } else {
                        setif_tv.setText(typeNames[iftype - 1] + "报警");
                    }
                    ifMac = bean.getConditionVos().get(0).getMac();
                    if (iftype == 1) {
                        ifPk = MsgID.PK_ALARM;
                    } else if (iftype == 2) {
                        ifPk = MsgID.PK_WATER;
                    } else if (iftype == 3) {
                        ifPk = MsgID.PK_SMOKE;
                    } else if (iftype == 4) {
                        ifPk = MsgID.PK_GAS;
                    } else if (iftype == 5) {
                        ifPk = MsgID.PK_DOOR;
                    }
                    if (thentype == 1) {
                        //                        setthen_tv.setText(typeNames[thentype - 1]+bean.getExcuteTaskVos().get(0).getMac().toUpperCase() + "报警");
                        setthen_tv.setText("报警器报警");
                    } else if (thentype == 6) {
                        //                        setthen_tv.setText(typeNames[thentype - 1] + "抓拍");
                        setthen_tv.setText("摄像机"+bean.getExcuteTaskVos().get(0).getMac()+"抓拍");
                    }

                    thenMac=bean.getExcuteTaskVos().get(0).getMac();

                    if (!TextUtils.isEmpty(bean.getScene_logic_name())) {
                        move_name.setText(bean.getScene_logic_name());
                    }
                }


                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<GetMoveInfoBean> call, Throwable t) {
                progressDialog.dismiss();
            }
        });
    }

    private void seListener() {
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        //        findViewById(R.id.title_right_img).setOnClickListener(this);
        findViewById(R.id.set_if_rl).setOnClickListener(this);
        findViewById(R.id.set_then_rl).setOnClickListener(this);
        findViewById(R.id.move_ok).setOnClickListener(this);

    }

    private void initView() {
        ((TextView) findViewById(R.id.title_tv)).setText("联动详情");
        setif_tv = (TextView) findViewById(R.id.setif_tv);
        setthen_tv = (TextView) findViewById(R.id.setthen_tv);
        move_name = (EditText) findViewById(R.id.move_name);
        scene_id = getIntent().getStringExtra("sceneID");
        move_tag = getIntent().getStringExtra("tag");
        mythenlist.clear();
        for (int i = 0; i < subList.size(); i++) {
            if (subList.get(i).getProductKey().equals(MsgID.PK_ALARM)) {
                mythenlist.add(subList.get(i));
            }
        }
    }


    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.move_ok:
                //场景设置完毕
                //                finish();
                moveName = move_name.getText().toString().trim();
                ifContent = setif_tv.getText().toString();
                thenContent = setthen_tv.getText().toString();
                if (TextUtils.isEmpty(moveName)) {
                    showToast("请输入联动名称");
                    return;
                }
                if (ifContent.equals("设置触发条件")) {
                    showToast("请设置触发条件");
                    return;
                }
                if (thenContent.equals("设置执行动作")) {
                    showToast("请设置执行动作");
                    return;
                }
                if (!TextUtils.isEmpty(move_tag)) {
                    //修改联动
                    changeMove();
                } else {
                    addMove();
                }

                break;
            case R.id.set_if_rl:
                //设置如果条件
                layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.set_if_dialog, null);
                alertDialog = new AlertDialog.Builder(this).create();

                ListView ifList = (ListView) layout.findViewById(R.id.if_list);
                iflistAdapter adapter = new iflistAdapter();
                ifList.setAdapter(adapter);

                ifList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                        nameIf = subList.get(i).getAlias();
                        macIf = subList.get(i).getMacAddress();
                        typeIf = subList.get(i).getProductKey();
                        if (typeIf.equals(MsgID.PK_DOOR)) {
                            setif_tv.setText((!TextUtils.isEmpty(nameIf) ? nameIf : subList.get(i).getProductName()) + "打开");
                        } else {
                            setif_tv.setText((!TextUtils.isEmpty(nameIf) ? nameIf : subList.get(i).getProductName()) + "报警");
                        }
                        alertDialog.dismiss();
                    }
                });

                alertDialog.show();

                alertDialog.setContentView(layout);
                Window window = alertDialog.getWindow();
                ViewGroup.LayoutParams layoutParams = window.getAttributes();
                WindowManager manager = window.getWindowManager();
                Display display = manager.getDefaultDisplay();
                layoutParams.width = (int) (display.getWidth() * 0.9);
                layoutParams.height = (int) (display.getHeight() * 0.5);
                window.setAttributes((WindowManager.LayoutParams) layoutParams);

                break;
            case R.id.set_then_rl:
                if (mythenlist.size() > 0 || cams.size() > 0) {
                    //设置执行条件
                    thenlayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.set_then_dialog, null);
                    alertDialog = new AlertDialog.Builder(this).create();

                    ListView thenList = (ListView) thenlayout.findViewById(R.id.then_list);
                    DoubleAdapter thenAdapter = new DoubleAdapter(mythenlist, cams);
                    thenList.setAdapter(thenAdapter);
                    thenList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            addMoveLgoic.ExcuteTasksBean excute = new addMoveLgoic.ExcuteTasksBean();
                            if (data.get(i) instanceof GizWifiDevice) {
                                GizWifiDevice device = (GizWifiDevice) data.get(i);
                                String thenType = device.getProductKey();
                                if (thenType.equals(MsgID.PK_ALARM)) {
                                    excute.setDevice_type(1);
                                    excute.setIdentification("AlarmStatus");
                                    if (typeIf.equals(MsgID.PK_DOOR)) {
                                        excute.setValue(0);
                                    } else if (typeIf.equals(MsgID.PK_WATER)) {
                                        excute.setValue(1);
                                    } else if (typeIf.equals(MsgID.PK_GAS)) {
                                        excute.setValue(2);
                                    } else if (typeIf.equals(MsgID.PK_SMOKE)) {
                                        excute.setValue(3);
                                    }
                                    excute.setMac(device.getMacAddress().toLowerCase());
                                    excuteTasks.add(excute);
                                    setthen_tv.setText(!TextUtils.isEmpty(device.getAlias()) ? device.getAlias() + "报警" : device.getProductName() + "报警");
                                }
                            } else {
                                //TODO 摄像头
                                CamListBean.DataBean cam = (CamListBean.DataBean) data.get(i);
                                excute.setDevice_type(6);
                                excute.setIdentification("");
                                excute.setValue(0);
                                excute.setMac(cam.getYst());
                                excuteTasks.add(excute);
                                setthen_tv.setText("摄像机"+cam.getYst() + "抓拍");
                            }

                            alertDialog.dismiss();
                        }
                    });

                    alertDialog.show();

                    alertDialog.setContentView(thenlayout);
                    Window window1 = alertDialog.getWindow();
                    ViewGroup.LayoutParams layoutParams1 = window1.getAttributes();
                    WindowManager manager1 = window1.getWindowManager();
                    Display display1 = manager1.getDefaultDisplay();
                    layoutParams1.width = (int) (display1.getWidth() * 0.9);
                    layoutParams1.height = (int) (display1.getHeight() * 0.5);
                    window1.setAttributes((WindowManager.LayoutParams) layoutParams1);

                    break;
                } else {
                    showToast("您还没有添加可联动的设备");
                }
        }
    }


    public void addMove() {
        progressDialog.show();
        /**
         * {
         "excuteTasks": [
         {
         "device_type": 0,
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "id": "string",
         "logicConditions": [
         {
         "campare": "string",
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "name": "string",
         "scene_id": "string"
         }

         门磁 DoorState true是门磁打开报警 false是关闭不报警 对应的值是true-1,false-0；
         水浸 WaterLine 0是不报警，1和2是报警；
         可燃气 AlarmStatus true是报警 false是不报警 对应的值是true-1,false-0；
         声光报警器 AlarmStatus，100是不报警；0、1、2、3都是报警，区分报警设备类型：0是门磁报警，1是水浸报警，2是可燃气报警，3是烟感报警；
         烟雾 SmokeAlarm true是报警 false是不报警 对应的值是true-1,false-0；


         */

        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();
        addMoveLgoic movelogic = new addMoveLgoic();

        addMoveLgoic.LogicConditionsBean logiccondition = new addMoveLgoic.LogicConditionsBean();

        if (typeIf.equals(MsgID.PK_DOOR)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("DoorState");
            logiccondition.setValue(0);
            logiccondition.setDevice_type(5);
        } else if (typeIf.equals(MsgID.PK_WATER)) {
            logiccondition.setCampare(">");
            logiccondition.setIdentification("WaterLine");
            logiccondition.setValue(0);
            logiccondition.setDevice_type(2);
        } else if (typeIf.equals(MsgID.PK_GAS)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("AlarmStatus");
            logiccondition.setValue(1);
            logiccondition.setDevice_type(4);
        } else if (typeIf.equals(MsgID.PK_ALARM)) {
            logiccondition.setCampare("<");
            logiccondition.setIdentification("AlarmStatus");
            logiccondition.setValue(4);
            logiccondition.setDevice_type(1);
        } else if (typeIf.equals(MsgID.PK_SMOKE)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("SmokeAlarm");
            logiccondition.setValue(1);
            logiccondition.setDevice_type(3);
        }
        logiccondition.setMac(macIf.toLowerCase());

        logicConditions.add(logiccondition);
        movelogic.setLogicConditions(logicConditions);

        movelogic.setExcuteTasks(excuteTasks);
        movelogic.setName(moveName);
        movelogic.setId("");
        movelogic.setScene_id(scene_id);

        String strEntity = gson.toJson(movelogic);
        if (logicConditions != null && logicConditions.size() > 0 && excuteTasks != null && excuteTasks.size() > 0) {
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
            Call<ResponseBody> call = service.addSceneLogic(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    showToast("联动添加成功");
                    MsgCenter.fireNull("scene", "");
                    progressDialog.dismiss();
                    if (NewSceneAct.instance != null) {
                        NewSceneAct.instance.finish();
                    }
                    finish();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    progressDialog.dismiss();
                    showToast("联动添加失败，请稍后重试");
                }
            });
        } else {
            progressDialog.dismiss();
            showToast("请设置触发条件或执行动作");
            return;
        }

    }

    public void changeMove() {
        progressDialog.show();
        /**
         * {
         "excuteTasks": [
         {
         "device_type": 0,
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "id": "string",
         "logicConditions": [
         {
         "campare": "string",
         "identification": "string",
         "mac": "string",
         "value": 0
         }
         ],
         "name": "string",
         "scene_id": "string"
         }

         门磁 DoorState true是门磁打开报警 false是关闭不报警 对应的值是true-1,false-0；
         水浸 WaterLine 0是不报警，1和2是报警；
         可燃气 AlarmStatus true是报警 false是不报警 对应的值是true-1,false-0；
         声光报警器 AlarmStatus，100是不报警；0、1、2、3都是报警，区分报警设备类型：0是门磁报警，1是水浸报警，2是可燃气报警，3是烟感报警；
         烟雾 SmokeAlarm true是报警 false是不报警 对应的值是true-1,false-0；
         */

        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Gson gson = new Gson();
        addMoveLgoic movelogic = new addMoveLgoic();

        addMoveLgoic.LogicConditionsBean logiccondition = new addMoveLgoic.LogicConditionsBean();
        if (TextUtils.isEmpty(typeIf)) {
            typeIf = ifPk;
        }
        if (typeIf.equals(MsgID.PK_DOOR)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("DoorState");
            logiccondition.setValue(0);
            logiccondition.setDevice_type(5);
        } else if (typeIf.equals(MsgID.PK_WATER)) {
            logiccondition.setCampare(">");
            logiccondition.setIdentification("WaterLine");
            logiccondition.setValue(0);
            logiccondition.setDevice_type(2);
        } else if (typeIf.equals(MsgID.PK_GAS)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("AlarmStatus");
            logiccondition.setValue(1);
            logiccondition.setDevice_type(4);
        } else if (typeIf.equals(MsgID.PK_ALARM)) {
            logiccondition.setCampare("<");
            logiccondition.setIdentification("AlarmStatus");
            logiccondition.setValue(4);
            logiccondition.setDevice_type(1);
        } else if (typeIf.equals(MsgID.PK_SMOKE)) {
            logiccondition.setCampare("=");
            logiccondition.setIdentification("SmokeAlarm");
            logiccondition.setValue(1);
            logiccondition.setDevice_type(3);
        }
        if (TextUtils.isEmpty(macIf)) {
            logiccondition.setMac(ifMac);
        }
        logiccondition.setMac(macIf);

        logicConditions.add(logiccondition);
        movelogic.setLogicConditions(logicConditions);
        if (excuteTasks.size() == 0) {
            addMoveLgoic.ExcuteTasksBean excute = new addMoveLgoic.ExcuteTasksBean();
            if (thentype == 1) {
                //报警器
                excute.setDevice_type(1);
                excute.setIdentification("AlarmStatus");
                if (typeIf.equals(MsgID.PK_DOOR)) {
                    excute.setValue(0);
                } else if (typeIf.equals(MsgID.PK_WATER)) {
                    excute.setValue(1);
                } else if (typeIf.equals(MsgID.PK_GAS)) {
                    excute.setValue(2);
                } else if (typeIf.equals(MsgID.PK_SMOKE)) {
                    excute.setValue(3);
                }
                excute.setMac(thenMac);
                excuteTasks.add(excute);
            } else if (thentype == 6) {
                //摄像头
                excute.setDevice_type(6);
                excute.setIdentification("");
                excute.setValue(0);
                excute.setMac(thenMac);
                excuteTasks.add(excute);
            }
        }
        movelogic.setExcuteTasks(excuteTasks);
        movelogic.setName(moveName);
        movelogic.setId(move_id);
        movelogic.setScene_id(scene_id);

        String strEntity = gson.toJson(movelogic);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        Call<ResponseBody> call = service.editSceneLogic(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                showToast("修改成功");
                MsgCenter.fireNull("scene", "");
                progressDialog.dismiss();
                finish();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                progressDialog.dismiss();
                showToast("修改失败，请稍后重试");
            }
        });
    }

    public class iflistAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return subList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView != null) {
                view = convertView;
            } else {
                view = LayoutInflater.from(MoveDetailAct.this).inflate(R.layout.move_iflist_item, parent, false);
            }

            ViewHolder holder = (ViewHolder) view.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.if_name_tv = (TextView) view.findViewById(R.id.if_name_tv);
                view.setTag(holder);
            }
            if (subList.get(position).getProductKey().equals(MsgID.PK_DOOR)) {

                holder.if_name_tv.setText((!TextUtils.isEmpty(subList.get(position).getAlias()) ? subList.get(position).getAlias() : subList.get(position).getProductName()) + "打开");
            } else {
                holder.if_name_tv.setText((!TextUtils.isEmpty(subList.get(position).getAlias()) ? subList.get(position).getAlias() : subList.get(position).getProductName()) + "报警");
            }
            return view;
        }

        public class ViewHolder {
            TextView if_name_tv;
        }
    }


    //整合数据
    private List<Object> data;

    public class DoubleAdapter extends BaseAdapter {
        public DoubleAdapter(List<GizWifiDevice> as, List<CamListBean.DataBean> bs) {
            data = new ArrayList<>();
            //把数据装载同一个list里面
            //这里把所有数据都转为object类型是为了装载同一个list里面好进行排序
            data.addAll(as);
            data.addAll(bs);
        }

        /**
         * 获得itemView的type
         *
         * @param position
         * @return
         */
        @Override
        public int getItemViewType(int position) {
            int result = 0;
            if (data.get(position) instanceof GizWifiDevice) {
                result = 0;
            } else if (data.get(position) instanceof CamListBean.DataBean) {
                result = 1;
            }
            return result;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            //根据position获得View的type
            int type = getItemViewType(position);
            if (convertView == null) {
                //实例化
                holder = new ViewHolder();

                convertView = View.inflate(MoveDetailAct.this, R.layout.move_iflist_item, null);
                holder.if_name_tv = (TextView) convertView.findViewById(R.id.if_name_tv);
                convertView.setTag(holder);

            } else {
                //根据不同的type来获得tag
                holder = (ViewHolder) convertView.getTag();
            }

            Object obj = data.get(position);
            //根据不同的type设置数据
            switch (type) {
                case 0:
                    GizWifiDevice device = (GizWifiDevice) obj;
                    holder.if_name_tv.setText((!TextUtils.isEmpty(mythenlist.get(position).getAlias()) ? mythenlist.get(position).getAlias() : mythenlist.get(position).getProductName()) + "报警");
                    break;

                case 1:
                    CamListBean.DataBean cam = (CamListBean.DataBean) obj;
                    holder.if_name_tv.setText("摄像机"+cam.getYst() + "抓拍");
                    break;
            }


            return convertView;
        }

        public class ViewHolder {
            TextView if_name_tv;
        }
    }

}
